<script>
 import {sharedParam} from '../stores/userStore'
 import {onMount} from 'svelte'
 import { writable } from 'svelte/store';
 
 import { createEventDispatcher } from 'svelte';

 let paramValue;
 let inputValue='';
 let searchers = {};
 const dispatch = createEventDispatcher();

 onMount(() => {
   const unsubscribe = sharedParam.subscribe(value => {
     paramValue = value;
   });

    return unsubscribe;
  });
  function updateParam() {
   sharedParam.set(false);
  }

function mission(){
   searchers.useris_banned = !searchers.useris_banned
}
let isopen = false;

async function fetchUserInfo() {
      if(inputValue==''){
        alert("请输入您要查询的值！")
        return
      }
      try {
        const response = await fetch('/api/chuangsong', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ inputValue }),
        });
      
        if (response.ok) {
          searchers = await response.json();
          isopen = true;
        } else {
          alert("查询失败！无该信息！")
        }
      } catch (error) {
        console.error('请求出错', error);
      }
    }
  
    $: {
      dispatch('updateUsers', searchers);
    }

    function checkPermission(param) {
    return param ? "禁止登录" : "允许登录";
  
}
let selectedAvatar;

async function handleSubmit(event) {
  event.preventDefault();
  if (!selectedAvatar) {
      // 用户没有选择头像
      alert("请先选择头像");
      return;
  }

  const formData = new FormData();
  formData.append('username', searchers.username);
  formData.append('password', searchers.userpassword);
  if (selectedAvatar) {
    formData.append('avatar', selectedAvatar);
  } else {
    formData.append('avatar', searchers.useravatar); // 或者根据后端接口的要求设置默认值
  }
  formData.append('email', searchers.useremail);
  formData.append('phone', searchers.userphone);
  formData.append('note', searchers.usernotes);
  formData.append('id',searchers.id)
  formData.append('is_banned',searchers.useris_banned)

  try {
    const response = await fetch('/api/UpdataUser', {
      method: 'POST',
      body: formData
    });

    if (response.ok) {
      // 请求成功，处理后端响应
      alert("修改成功！")
      dispatch('success');
    } else {
      // 请求失败，处理错误情况
      dispatch('error');
    }
  } catch (error) {
    // 请求发送失败，处理发送失败情况
    dispatch('error');
  }
}
//定义一个点击按钮就可以

</script>

{#if Boolean(paramValue)}
<main>
  <h1 class="welcome-text">欢迎来到修改页面</h1>
  <h1 class="welcome-text">请输入您要修改用户的用户名：</h1>
  <form >
    <input type="text" placeholder="请输入用户名"  bind:value={inputValue } required />
    <button on:click={fetchUserInfo}>确认</button>
</form>
</main>
  {#if isopen}
<img src={`data:image/jpg;base64,${searchers.useravatar}`} alt={searchers.username} class="avatar" />
<label>修改头像</label>
<input type="file" accept="image/jpeg, image/png"  on:change={(event) => selectedAvatar = event.target.files[0]}/>
<label for="username">用户名</label>
<input type="text" id="username" bind:value={searchers.username} />

<label for="password">用户密码</label>
<input type="text" id="password" bind:value={searchers.userpassword} />

<label for="email">用户邮箱</label>
<input type="email" id="email" bind:value={searchers.useremail} />

<label for="phone">用户电话</label>
<input type="tel" id="phone" bind:value={searchers.userphone} />

<label for="note">用户备注</label>
<textarea id="note" bind:value={searchers.usernotes}></textarea>
<br/>
<c>用户是否允许登录：</c>
<button on:click={mission}>{checkPermission(searchers.useris_banned)}</button>
<br/>
<button on:click={handleSubmit}>保存</button>
  {/if}


{:else}
  <p>请先登录</p>
  <a href="/login">登录</a>

{/if}

<style>

.welcome-text {
  font-family: 'Comic Sans MS', cursive;
  font-size: 32px;
  color: red;
  margin-bottom: 20px;
}
.avatar {
  border-radius: 50%;
  width: 100px; /* 设置图片的宽度 */
  height: 100px; /* 设置图片的高度 */
  object-fit: cover; /* 确保图片在容器中完整显示 */
}
p
  {
    font-size: 15px;
      font-weight: bold;
      text-align: center;
      padding: 20px;
      background-color: #007bff;
      color: #fff;
  }

</style>

